package org.example.command;



import org.example.exception.HTMLDocumentException;
import org.example.model.HTMLDocument;
import org.jsoup.nodes.Element;

public class AppendElementCommand implements CanUndoCommand {

    private final String tagName;
    private final String elementId;
    private final String parentId;
    private final String textContent;
    private HTMLDocument htmlDocument;
    private Element addedElement;

    private AppendElementCommand(HTMLDocument htmlDocument, String tagName, String elementId, String parentId, String textContent) {
        this.tagName = tagName;
        this.elementId = elementId;
        this.parentId = parentId;
        this.textContent = textContent;
        this.htmlDocument = htmlDocument;
    }

    public static Command create(HTMLDocument htmlDocument, String tagName, String elementId, String parentId, String textContent) {
        return new AppendElementCommand(htmlDocument, tagName, elementId, parentId, textContent);
    }

    @Override
    public boolean execute() {

        try {
            // 记录添加的元素，以便撤销时删除
            addedElement = htmlDocument.appendElement(tagName, elementId, parentId, textContent);
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
            return false;
        }
        return true;
    }

    @Override
    public void undo() {
        // 使用 HTMLDocument 提供的删除元素功能
        try {
            if (addedElement != null) {
                htmlDocument.deleteElement(addedElement.id());
            }
        } catch (HTMLDocumentException e) {
            System.out.println(e.getMessage());
        }
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 37 * hash + (this.elementId != null ? this.elementId.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final AppendElementCommand other = (AppendElementCommand) obj;
        if ((this.elementId == null) ? (other.elementId != null) : !this.elementId.equals(other.elementId)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "AppendElementCommand{" + "tagName=" + tagName + ", elementId=" + elementId + ", parentId=" + parentId + ", textContent=" + textContent + '}';
    }
}
